require 'http'
class Repository

  Gitee = 'https://gitee.com'
  GiteeOpenAPI = "#{Gitee}/api/v5"

  attr_reader :dirs, :repository_user, :token, :repository_list


  def initialize(dirs, repository_user, token)
    @dirs = dirs
    @repository_user = repository_user
    @token = token
    gitee_all_repository
    self
  end

  def auto_run  
    @dirs.each do |dir|
      unless is_git_rep?(dir)
        puts "#{dir} is not git repository"
      else
        git_job(dir)
      end
    end
  end

private
  def is_git_rep?(dir)
    return Dir.exist?("#{dir}/.git") && !Dir.empty?("#{dir}/.git")
  end



  def repository_vaild_and_create(name)
    if repository_exists? name
      puts "#{Gitee}/#{@repository_user}/#{name} is exists"
      return nil
    end
    new_name = create_repository name
    if new_name == ''
      puts "#{Gitee}/#{@repository_user}/#{new_name} is exists"
      return nil
    end
    new_name
  end

  def git_job(dir)
    `git config http.postBuffer 524288000`
    Dir.chdir(dir) do
      l = `git remote -v|awk '{print $2}'`
      if l.nil? || l.empty?
        new_name = repository_vaild_and_create dir
        next if new_name == nil
        `git remote add origin #{Gitee}/#{@repository_user}/#{new_name}.git`
      else
        origin_addr = l.split("\n").first
        if origin_addr == "#{Gitee}/#{@repository_user}/.git"
          origin_addr = "#{Gitee}/#{@repository_user}/#{dir}.git"
        end
        repository_name = origin_addr.split("/")[-1].chomp(".git")
        new_name = repository_vaild_and_create repository_name
        next if new_name == nil
        File.open("#{dir}/gitrepository.copy", 'w'){|file| file.write origin_addr }
        `git remote set-url origin #{Gitee}/#{@repository_user}/#{new_name}.git`
      end
      `git push --all origin`
    end
  end

  def repository_exists?(name)
    @repository_list.include? name
  end

  def create_repository(name)
    body = HTTP.post("#{GiteeOpenAPI}/user/repos", form: {
      access_token: @token,
      name: name,
      private: true
    }).parse
    (body["error"].nil? || body["error"].empty?) ? body["name"] : ''
  end

  def gitee_all_repository
    response = HTTP.get("#{GiteeOpenAPI}/user/repos", params: {
      visibility: 'all',
      access_token: @token,
      affiliation: 'owner',
      per_page: 1000
    })
    list =  response.parse
    @repository_list = list.map{|item| item["name"]}
  end

end